package org.qydjk.h5.filter;

import org.qydjk.common.constant.CommonConstant;
import org.qydjk.common.pojo.user.User;
import org.qydjk.common.util.CookieUtil;
import org.qydjk.common.util.DESUtil;
import org.qydjk.common.util.SpringContextUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.service.service.customerCenter.ICustomerCenterHomePageService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Cookie记住登录
 */
public class CookieLoginFilter implements Filter{
    private static ICustomerCenterHomePageService customerCenterHomePageService;

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        //从session里面查找用户信息
        String userId = (String) session.getAttribute(CommonConstant.COMMON_USER_SESSION_NAME);
        if(StringUtil.isEmptyOrNull(userId)){
            //session无用户信息，从cookie获取
            String userCookie = CookieUtil.getCooklieValue(request, CommonConstant.COMMON_LOGIN_COOKIE_NAME);
            if(!StringUtil.isEmptyOrNull(userCookie)){
                //cookie有用户信息，拿来登录
                try {
                    userId = DESUtil.decrypt(userCookie,CommonConstant.COMMON_LOGIN_COOKIE_DES_KEY);
                    if(!StringUtil.isEmptyOrNull(userId)){
                        int userIdInt = Integer.parseInt(userId);
                        if(customerCenterHomePageService == null){
                            customerCenterHomePageService = (ICustomerCenterHomePageService) SpringContextUtil.getBean("customerCenterHomePageService");
                        }
                        User user = customerCenterHomePageService.getCustomerInfo(userIdInt);
                        if(user != null){
                            session.setAttribute(CommonConstant.COMMON_USER_SESSION_NAME,userId);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    public void destroy() {

    }
}
